import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { start, close } from '@/assets/js/nprogress'
import Storage from '@/assets/js/storage'

const routerHistory = createWebHistory('/scb/')

const router = createRouter({
  history: routerHistory,
  routes,
})

router.beforeEach((to, from, next) => {
  // start()
  // 每次进入页面都加上新的时间戳
  const newQuery = {
    ...to.query,
    t: Date.now(),
  }

  // 只有当时间戳不同的时候才跳转，避免死循环
  if (to.query.t !== String(newQuery.t)) {
    next({
      ...to,
      query: newQuery,
      replace: true, // 避免 push 产生多余历史记录
    })
    return
  }
  next()
  // if (!Storage.get('access_token')) {
  //   if (to.meta.required) {
  //     let query = from.query
  //     query.urlName = from.name
  //     router.push({
  //       name: 'login',
  //       query: query,
  //     })
  //   } else {
  //     next()
  //   }
  // } else {
  //   next()
  // }
})

router.afterEach(() => {
  // close()
  const scrollContainer = document.querySelector('.el-scrollbar__wrap')
  if (scrollContainer) {
    scrollContainer.scrollTo({ top: 0 })
  }
})

export default router
